// pages/order/index.js
Page({
  data: {
    app:null,
    db:null,
    userInfo:{},
    isLoggedIn:false,
    currentTab:0,
    orderList:[],
    backHome:false,
  },
  onUnload(){
    console.log('onUnload   onUnload',this.data.backHome)
    if(this.data.backHome){
        wx.reLaunch({ url: '/pages/business/index' })
    }
  },
  onLoad(options) {
    const app = getApp();
    this.setData({
      app:app
    })
    console.log(app.globalData.env); // 输出: your-env-id
    // 获取默认环境的数据库引用
    this.setData({
      db:app.globalData.db
    })
    const userInfo = wx.getStorageSync('userInfo');
    console.log('business userInfo',userInfo)
    this.setData({
      isLoggedIn: !!userInfo,
      userInfo: userInfo || {},
    });
    if(options.currentTab){
      this.setData({
        currentTab:Number(options.currentTab)
      })
      app.globalData.currentTab = this.data.currentTab
    }
    if(options.back){
      this.setData({
        backHome:true
      })
    }
    
    if(options.id){
      wx.showLoading({ title: '加载中...' })
      this.data.db.collection('goodsList').where({
        _id:options.id
      }).get()
    .then(res => {
      if(res && res.data && res.data.length > 0){
        console.log('res',res.data,this.data.currentTab)
        this.setData({
          orderList:res.data.map(item => ({
            ...item,
            formattedTime: this.getFormats(item.createTime),
            allCount:item.goodsList.reduce((total, item) => total + Number(item.num), 0),
            allPrice:item.goodsList.reduce((total, item) => total + Number(item.price), 0)
          }))
        })
      }
    })
    .catch (err =>  {
      wx.showToast({ title: '加载失败', icon: 'none' })
    })
    .finally(() => {
      wx.hideLoading()
    }) 
    }
  },
  getFormats(timestamp) {
    const date = new Date(timestamp);
  
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  // 切换标签页
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.currentTab === index) return;
    
    this.setData({
      currentTab: index,
      noMore: false,
      lastDoc:null,
      orderList:[],
    }, () => {
      this.loadOrderList(true);
    });
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/index?id=${orderId}`,
    })
  },

  // 取消订单
  cancelOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要取消此订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' });
          this.data.db.collection('goodsList').doc(orderId).update({
            data: {
              status:'已取消'
            },
            success: res => {
              wx.hideLoading();
              this.updateOrderStatus(orderId, '已取消');
              wx.showToast({ title: '取消成功', icon: 'success' });
            },
            fail: err => {
              wx.hideLoading()
              wx.showToast({
                title: '取消失败',
                icon: 'none'
              })
            }
          })
        }
      }
    });
  },
  delete(e){
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除此订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: `删除中...`,
          })
          this.data.db.collection('goodsList').doc(orderId).remove({
            success: res => {
              wx.hideLoading();
              this.updateOrderStatus(orderId, '已删除');
              wx.showToast({ title: '删除成功', icon: 'success' });
            },
            fail: err => {
              wx.hideLoading()
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  // 确认收货
  confirmReceipt(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showLoading({ title: '处理中...' });
    this.data.db.collection('goodsList').doc(orderId).update({
      data: {
        status:'已完成'
      },
      success: res => {
        wx.hideLoading();
        this.updateOrderStatus(orderId, '已完成');
        wx.showToast({ title: '操作成功', icon: 'success' });
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    })
  },

  // 查看物流
  viewLogistics(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/order/logistics?id=${orderId}`
    });
  },

  // 更新订单状态
  updateOrderStatus(orderId, newStatus) {
    if(newStatus === '已删除'){
      this.setData({
        orderList: this.data.orderList.filter(order => {
          return order._id !== orderId
        })
      });
    }else{
      this.setData({
        orderList: this.data.orderList.map(order => {
          if (order._id === orderId) {
            return { ...order, status: newStatus };
          }
          return order;
        })
      });
    }

  },
  // 跳转到详情页
  viewOrderDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/show/index?id=${id}`
    });
  },
});